package eu.gegenleitner.esspacc.ca;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class CSRChecker {
	
	public final static String gNameStartKey = "=givenname=";
	public final static String gNameEndKey = "=/givenname=";
	public final static String sNameStartKey = "=surname=";
	public final static String sNameEndKey = "=/surname=";
	public final static String emailStartKey = "=email=";
	public final static String emailEndKey = "=/email=";
	public final static String pubKeyStartKey = "=pubkey=";
	public final static String pubKeyEndKey = "=/pubkey=";
	
	private String givenName;
	private String surName;
	private String eMailAddress;
	private PublicKey pubKey;
	
	public CSRChecker(String csr) throws InvalidKeySpecException, NoSuchAlgorithmException, Base64DecodingException {
		givenName = csr.substring(csr.indexOf(gNameStartKey) + gNameStartKey.length(),csr.indexOf(gNameEndKey));
		surName = csr.substring(csr.indexOf(sNameStartKey) + sNameStartKey.length(),csr.indexOf(sNameEndKey));
		eMailAddress = csr.substring(csr.indexOf(emailStartKey) + emailStartKey.length(),csr.indexOf(emailEndKey));
		pubKey = KeyFactory.getInstance("RSA")
				.generatePublic(new X509EncodedKeySpec(
						Base64.decode(
								csr.substring(csr.indexOf(pubKeyStartKey) + pubKeyStartKey.length(),csr.indexOf(pubKeyEndKey))
						)));
	}

	public boolean isValidCSR() {
		/*TODO: InputValidation*/
		if( !givenName.isEmpty()
				&& !surName.isEmpty()
				&& !eMailAddress.isEmpty()
				&& pubKey != null)
			return true;
		return false;
	}
	
	public String getGivenName() {
		return givenName;
	}
	
	public String getSurName() {
		return surName;
	}
	
	public String getMailAddress() {
		return eMailAddress;
	}
	
	public PublicKey getPublicKey() {
		return pubKey;
	}
}
